class VisibleOrderToUser < ActiveRecord::Base
  
  include DynamicDefaultScoping
  
  validates :enterprise_id, :presence => true
  validates :order_id,
    :user_id,
    :presence => true
  
  belongs_to :order
  belongs_to :user
  
  default_scope :current_enterprise,lambda { 
    where(
      :enterprise_id => Enterprise.current_id 
    )
  }

  after_create do |m|
    visible_order_to_users = VisibleOrderToUser.where(:order_id => nil, :enterprise_id => Enterprise.current_id)
    VisibleOrderToUser.destroy(
       visible_order_to_users.each_with_object([]) do |obj, values|
         values << obj.id
       end
    )
    VisibleOrderToGroup.destroy_by_order_id(m.order_id)
  end

  def self.destroy_by_order_id(order_id)
    visible_order_to_users = VisibleOrderToUser.where(:order_id => order_id, :enterprise_id => Enterprise.current_id)
    VisibleOrderToUser.destroy(
       visible_order_to_users.each_with_object([]) do |obj, values|
         values << obj.id
       end
    )
  end
end
